package cn.hongwei.nacos.handler.base;

import cn.hongwei.nacos.context.InstanceContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Great
 * @email 1224028994@qq.com
 *
 */
public abstract class InstanceBaseHandler<E> {
    @Autowired
    protected OkHttpClient okHttpClient;

    @Autowired
    protected ObjectMapper objectMapper;

    private InstanceBaseHandler nextHandler;

    public void next(InstanceBaseHandler instanceBaseHandler){
        this.nextHandler=instanceBaseHandler;
    }

    public abstract void doHandler(InstanceContext instanceContext);

    protected void doNextHandler(InstanceContext instanceContext){
        if(nextHandler!=null){
            nextHandler.doHandler(instanceContext);
        }
    }

    /**
     * 构建者模式
     * @param <E>
     */
    public static class Builder<E> {
        private InstanceBaseHandler<E> head;
        private InstanceBaseHandler<E> tail;

        public Builder<E> addHandler(InstanceBaseHandler<E> handler) {
            if (this.head == null) {
                this.head = this.tail = handler;
                return this;
            }
            this.tail.next(handler);
            this.tail = handler;
            return this;
        }

        public void clean(){
            this.head = null;
            this.tail = null;
        }

        public InstanceBaseHandler<E> build() {
            return this.head;
        }
    }
}
